package qr.game.fragments;

import java.util.List;

import qr.core.Location;
import qr.game.LocationViewActivity;
import qr.game.R;
import qr.game.rest.RestClient;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class LocationListAdapter extends BaseAdapter {

	RestClient cl;
	Context c;

	LocationListAdapter( Context c ) {
		this.c = c;
		cl = RestClient.getRestClient();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		String un = c.getSharedPreferences("qrcode", Context.MODE_MULTI_PROCESS ).getString("username", "");
		List<Location> foundLocations = cl.getFoundLocations( un );
		Log.d("location", "found:" + foundLocations.size() );
		final Location l = cl.getLocations().get(position);
		LayoutInflater li = LayoutInflater.from(c);
		View cv = li.inflate( R.layout.locations_entry, null );
		TextView locName = (TextView) cv.findViewById(R.id.location_name);
		TextView locClue = (TextView) cv.findViewById(R.id.location_clue);
		ImageView image = (ImageView) cv.findViewById(R.id.imageView1);
		if( foundLocations.contains(l) ){
			image.setImageResource( R.drawable.found );
			cv.setOnClickListener( new OnClickListener(){

				@Override
				public void onClick(View v) {
					if( foundLocation(l) ){
						Intent next = new Intent( c, LocationViewActivity.class );
						next.putExtra("location", l.getId() + "" );
						c.startActivity(next);
					}
				}
				
				private boolean foundLocation( Location l ){
					String un = c.getSharedPreferences("qrcode", Context.MODE_MULTI_PROCESS ).getString("username", "");
					List<Location> foundLocations = cl.getFoundLocations( un );
					return foundLocations.contains(l);
				}
				
			});
		}else{
			image.setVisibility(View.INVISIBLE);
		}
		locName.setText( l.getName() );
		locClue.setText( l.getClue() );

		return cv;
	}

	@Override
	public int getCount() {
		return cl.getLocations().size();
	}

	@Override
	public Object getItem(int position) {
		return cl.getLocations().get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

}

